//
//  HMBaseViewController.swift
//  SinaWeiBo
//
//  Created by immncjykeny on 2017/4/21.
//  Copyright © 2017年 immncjykeny. All rights reserved.
//

import UIKit

class HMBaseViewController: UIViewController {
    
    //标记一个访客视图字典信息
    var visitorInfoDictionary:[String:String]?
    
    var tableView:UITableView?
    //上拉加载刷新标记
    var isPullUp = false
    
    //用户是否登录访客视图
    //var userLogin = true
    
    var refleshControl:UIRefreshControl?//定义一个下拉刷新控件
    //自定义navigationBar
    lazy var navigaBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    //自定义navigationItem导航条
    //lazy var navItem = UINavigationItem()
    lazy var navigaItem:UINavigationItem = {
        let navItem = UINavigationItem()
        
        return navItem
    }()
   

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        //取消自动缩进
        automaticallyAdjustsScrollViewInsets = false
        
        HMShareManager.shared.userlogon ? loadData() : ()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: HMUserLoginSuccessNotification), object: nil)
    }
    
    
     //销毁通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //父类写个方法 由子类来实现
    func loadData(){
        //如果子类不是任何方法 默认关闭刷新控件
        refleshControl?.endRefreshing()
        
    }
    //重写title 的didSet方法
    override var title: String?{
        didSet{
            navigaItem.title = title
        }
    }

}
extension HMBaseViewController{
    
    //登录成功后处理通知
    @objc fileprivate func loginSuccess(n:Notification){
        
        print("登录成功\(n)")
        //删除注册和登录
        navigaItem.leftBarButtonItem = nil
        navigaItem.rightBarButtonItem = nil
        //刷新UI 访客视图替换成列表视图
        //view =nil 意味着执行loadView--> 在执行viewdidLoad
        view = nil
        //这行代码为了防止通知重复注册 因为会执行viewdidload 在被再次注册通知
        NotificationCenter.default.removeObserver(self)
        
    }
    
    @objc fileprivate func loginAction(){
        print("用户登录")
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: HMUserShouldLoginNotification), object: nil)
    }
    @objc fileprivate func registerAction(){
        print("用户注册")
    }
}
extension HMBaseViewController{
   fileprivate func setupUI()  {
        view.backgroundColor = UIColor.cz_random()
    
        setupNavigationBar()
    
        HMShareManager.shared.userlogon ? setupTableView() : setupVisitorView()
        
    }
     func setupTableView(){
        tableView = UITableView(frame: view.bounds, style: .plain)
        view.insertSubview(tableView!, belowSubview: navigaBar)
        tableView?.dataSource = self
        tableView?.delegate = self
        
        //设置内容缩进
        tableView?.contentInset = UIEdgeInsets(top: navigaBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        //修改指示器缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        //创建下拉刷新控件
        refleshControl = UIRefreshControl()
        //添加表格视图
        tableView?.addSubview(refleshControl!)
        //只要继承UIControl可以直接添加监听方法
        refleshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
 
    
    /// 设置访客视图
    private func setupVisitorView(){
        let visitorView = HMVisitorView(frame: view.bounds)
        
        
        view.insertSubview(visitorView, belowSubview: navigaBar)
        
        visitorView.visitorInfo = visitorInfoDictionary
        
        visitorView.loginButton.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(registerAction), for: .touchUpInside)
        navigaItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(registerAction))
        navigaItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(loginAction))
        
        
        
        
    }
    private func setupNavigationBar(){
        //添加导航条
        view.addSubview(navigaBar)
        
        navigaBar.items = [navigaItem]
        
        navigaBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        
        navigaBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        
        navigaBar.tintColor = UIColor.orange
    }
}
extension HMBaseViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        return UITableViewCell()
    }
    //在显示最后一行 做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //判断indexPath是否是最后一行 一个是indexPath.row（最后一行） 一个是indexPath.section(最大)
        let row = indexPath.row
        
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
            return
        }
        //行数
        let count = tableView.numberOfRows(inSection: section)
        //如果是最后一行 并且没有上拉刷新 我们才能判断上拉刷新
        if row == (count - 1) && !isPullUp {
            
            print("上拉刷新")
            
            isPullUp = true
            
             loadData()
        }
        
       
        
        
    }
}
